﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using MSNPSharp;

namespace TienLen.UC
{
    /// <summary>
    /// User control for MainMenu, which handles logging into MSN.
    /// </summary>
    public partial class MSNLogin : UserControl
    {
        private MainMenu parentfrm;

        public MSNLogin(MainMenu mainfrm)
        {
            if (SvrFunc.MSN == null)
                SvrFunc.MSN = new Messenger();

            // Prepare MSNPSharp settings
            Settings.NoSave = TienLen.Properties.Settings.Default.opt_msnnosave;
            if (!TienLen.Properties.Settings.Default.opt_msnnosave)
            {
                switch (TienLen.Properties.Settings.Default.opt_msnsavetype)
                {
                    case 0:
                        Settings.SerializationType = MSNPSharp.IO.MclSerialization.None;
                        break;
                    case 1:
                        Settings.SerializationType = MSNPSharp.IO.MclSerialization.Compression;
                        break;
                    case 2:
                        Settings.SerializationType = MSNPSharp.IO.MclSerialization.Cryptography;
                        break;
                    case 3:
                        Settings.SerializationType = MSNPSharp.IO.MclSerialization.Compression | MSNPSharp.IO.MclSerialization.Cryptography;
                        break;
                }
            }

            // Add the MSN events. They are removed in the Dispose() event (MSNLogin.Designer)
            SvrFunc.MSN.Nameserver.AuthenticationError += new EventHandler<ExceptionEventArgs>(MSN_AuthException);
            SvrFunc.MSN.Nameserver.SignedIn += new EventHandler<EventArgs>(Nameserver_SignedIn);

            InitializeComponent();

            txtUsr.KeyPress += new KeyPressEventHandler(btnLogin_KeyPress);
            txtPass.KeyPress += new KeyPressEventHandler(btnLogin_KeyPress);
            btnLogin.KeyPress += new KeyPressEventHandler(btnLogin_KeyPress);

            parentfrm = mainfrm;
            mainfrm.BackButton.Visible = true;

            pic1.Image = Image.FromFile(Application.StartupPath + @"\img\other\wlm.png");
            pic2.Image = Image.FromFile(Application.StartupPath + @"\img\other\wlm-text.png");

            cmbStatus.SelectedIndex = 0;

            ChangeGUI(true);

            if (TienLen.Properties.Settings.Default.msn_usrname != string.Empty)
            {
                txtUsr.Text = TienLen.Properties.Settings.Default.msn_usrname;
                chkRem.Checked = true;
            }
        }

        /// <summary>
        /// Change the state of controls, depending if the user is logging in or not.
        /// </summary>
        /// <param name="idle">If false, you are attempting to login.</param>
        private void ChangeGUI(bool idle)
        {
            txtUsr.Enabled = idle;
            txtPass.Enabled = idle;
            cmbStatus.Enabled = idle;
            chkRem.Enabled = idle ? txtUsr.Text != string.Empty : false;

            parentfrm.BackButton.Enabled = idle;
            parentfrm.OptionButton.Enabled = idle;

            btnLogin.Text = idle ? "Login" : "Cancel";
            parentfrm.InfoText = idle ? string.Empty : "Logging in...";

            if (!idle)
            {
                btnLogin.MouseEnter -= btnLogin_MouseEnter;
                btnLogin.MouseLeave -= parentfrm.Button_MouseLeave;
            }
            else
            {
                btnLogin.MouseEnter += new EventHandler(btnLogin_MouseEnter);
                btnLogin.MouseLeave += new EventHandler(parentfrm.Button_MouseLeave);
            }
        }

        private void btnLogin_MouseEnter(object sender, EventArgs e)
        {
            parentfrm.InfoText = "Log into MSN to play Tien Len";
        }

        private void login_Click(object sender, EventArgs e)
        {
            switch (btnLogin.Text)
            {
                case "Login":
                    {
                        try
                        {
                            SvrFunc.MSN.Credentials = new Credentials(txtUsr.Text, txtPass.Text);
                            SvrFunc.MSN.Connect();

                            ChangeGUI(false);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Problem logging into MSN", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }

                        break;
                    }
                case "Cancel":
                    {
                        SvrFunc.MSN.Disconnect();
                        ChangeGUI(true);
                        break;
                    }
            }      
        }

        private void Nameserver_SignedIn(object sender, EventArgs e)
        {
            if (InvokeRequired) BeginInvoke(new EventHandler<EventArgs>(Nameserver_SignedIn), sender, e);
            else
            {
                if (chkRem.Checked)
                {
                    TienLen.Properties.Settings.Default.msn_usrname = txtUsr.Text;
                    TienLen.Properties.Settings.Default.Save();
                }

                GC.Collect();

                new MSNClient((PresenceStatus)Enum.Parse(typeof(PresenceStatus), cmbStatus.Text)).Show();

                parentfrm.SuppressExit = true;
                parentfrm.Close();
            }
        }

        private void MSN_AuthException(object sender, ExceptionEventArgs e)
        {
            if (InvokeRequired) Invoke(new EventHandler<ExceptionEventArgs>(MSN_AuthException));
            else
            {
                MessageBox.Show("Your account couldn't be connected to the MSN server." + Environment.NewLine +
                    "Check your e-mail address and password.", "Authentication Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                ChangeGUI(true);
            }
        }

        private void btnLogin_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r') login_Click(null, EventArgs.Empty);
        }

        private void chkRem_CheckedChanged(object sender, EventArgs e)
        {
            if (!chkRem.Checked)
            {
                TienLen.Properties.Settings.Default.msn_usrname = string.Empty;
                TienLen.Properties.Settings.Default.Save();

                txtUsr.Text = string.Empty;
                txtPass.Text = string.Empty;
            }
        }

        private void txtUsr_TextChanged(object sender, EventArgs e)
        {
            chkRem.Enabled = !string.IsNullOrEmpty(txtUsr.Text.Trim());
        }
    }
}
